import sys
import time
from typing import Optional
from core.models import ScanStatistics
from config.settings import PROGRESS_BAR_LENGTH, REFRESH_INTERVAL

class ProgressDisplay:
    """进度显示器"""
    
    def __init__(self):
        self.last_refresh = 0
        self.start_time = time.time()
        
    def display_progress(self, stats: ScanStatistics, current_path: Optional[str] = None):
        """显示扫描进度
        
        Args:
            stats: 扫描统计信息
            current_path: 当前扫描路径
        """
        # 控制刷新频率
        current_time = time.time()
        if current_time - self.last_refresh < REFRESH_INTERVAL:
            return
        
        self.last_refresh = current_time
        
        # 计算已用时间
        elapsed_time = current_time - self.start_time
        
        # 清空当前行并显示进度
        sys.stdout.write('\r' + ' ' * 100 + '\r')
        
        # 显示基本信息
        info = f"文件数量: {stats.total_files:,}   目录数量: {stats.total_directories:,}   "
        info += f"已用时间: {self._format_time(elapsed_time)}"
        
        # 如果有当前路径，显示它
        if current_path:
            path_info = f"\n当前路径: {current_path}"
            sys.stdout.write(path_info)
        
        # 刷新输出
        sys.stdout.write(info)
        sys.stdout.flush()
    
    def _format_time(self, seconds: float) -> str:
        """格式化时间显示
        
        Args:
            seconds: 秒数
        
        Returns:
            格式化的时间字符串 (HH:MM:SS)
        """
        hours, remainder = divmod(int(seconds), 3600)
        minutes, seconds = divmod(remainder, 60)
        return f"{hours:02d}:{minutes:02d}:{seconds:02d}"
    
    def finish(self):
        """完成进度显示"""
        print()  # 换行